package org.vison.wonfu.framework.codestyle.core;

import com.github.javaparser.ast.CompilationUnit;
import org.vison.wonfu.framework.codestyle.config.CheckerConfig;
import org.vison.wonfu.framework.codestyle.issue.IssueCollector;
import org.vison.wonfu.framework.codestyle.rules.CodeCheckRule;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * 代码检查核心框架，负责加载和运行所有检查规则
 */
public class CheckerFramework {
    private final CheckerConfig config;
    private final List<CodeCheckRule> rules = new ArrayList<>();
    private final IssueCollector issueCollector = new IssueCollector();

    public CheckerFramework(CheckerConfig config) {
        this.config = config;
        loadRules();
    }

    /**
     * 加载所有可用的检查规则
     */
    private void loadRules() {
        // 使用ServiceLoader自动发现并加载所有实现了CodeCheckRule接口的类
        ServiceLoader<CodeCheckRule> ruleLoader = ServiceLoader.load(CodeCheckRule.class);
        
        for (CodeCheckRule rule : ruleLoader) {
            // 根据配置决定是否启用该规则
            if (isRuleEnabled(rule)) {
                rule.initialize(config);
                rules.add(rule);
                System.out.println("已加载检查规则: " + rule.getName());
            }
        }
    }

    /**
     * 检查规则是否在配置中启用
     */
    private boolean isRuleEnabled(CodeCheckRule rule) {
        return config.isRuleEnabled(rule.getId());
    }

    /**
     * 检查单个Java文件
     */
    public void checkFile(File file, CompilationUnit compilationUnit) {
        for (CodeCheckRule rule : rules) {
            rule.check(file, compilationUnit, issueCollector);
        }
    }

    /**
     * 获取所有检查结果
     */
    public IssueCollector getIssueCollector() {
        return issueCollector;
    }

    /**
     * 获取已加载的规则数量
     */
    public int getLoadedRulesCount() {
        return rules.size();
    }
}
